package com.org.util.email;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.org.util.PropertiesUtil;
import com.sun.xml.messaging.saaj.packaging.mime.internet.MimeUtility;

/**
 * 简单邮件（不带附件的邮件）发送器
 */
public class SimpleMailSender implements Runnable {
	private static Log logger = LogFactory.getLog(SimpleMailSender.class);
	private static ExecutorService  executor = Executors.newFixedThreadPool(10);

	/**
	 * 以文本格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件的信息
	 * @throws UnsupportedEncodingException
	 * @throws MessagingException
	 */
	@SuppressWarnings("static-access")
	public boolean sendTextMail(MailSenderInfo mailInfo) throws UnsupportedEncodingException, MessagingException {
		// 判断是否需要身份认证
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份认证，则创建一个密码验证器
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		// Session sendMailSession =
		// Session.getDefaultInstance(pro,authenticator);
		Session sendMailSession = Session.getInstance(pro, null);
		// sendMailSession.setDebug(true);
		Transport transport = sendMailSession.getTransport("smtp");

		MimeMessage mimeMessage = new MimeMessage(sendMailSession);

		// 根据session创建一个邮件消息
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		// 设置邮件消息的发送者
		messageHelper.setFrom(new InternetAddress(mailInfo.getFromAddress()));
		// 创建邮件的接收者地址，并设置到邮件消息中
		messageHelper.setTo(new InternetAddress(mailInfo.getToAddress()));
		// 抄送者地址
		if (mailInfo.getToccAddress() != null && !"".equals(mailInfo.getToccAddress())) {
			messageHelper.setCc(new InternetAddress(mailInfo.getToccAddress()));
		}
		// 密送者地址
		if (mailInfo.getTobccAddress() != null && !"".equals(mailInfo.getTobccAddress())) {
			messageHelper.setBcc(new InternetAddress(mailInfo.getTobccAddress()));
		}
		// 回复邮箱地址
		if (mailInfo.getToReplyAddress() != null && !"".equals(mailInfo.getToReplyAddress())) {
			messageHelper.setReplyTo(new InternetAddress(mailInfo.getToReplyAddress()));
		}
		// 设置邮件消息的主题
		messageHelper.setSubject(mailInfo.getSubject());
		// 设置邮件消息发送的时间
		messageHelper.setSentDate(new Date());
		// 设置邮件发送附件
		mimeMessage = messageHelper.getMimeMessage();
		String[] filenames = mailInfo.getAttachFileNames();
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对象
		// 把mm作为消息对象的内容
		MimeBodyPart filePart = null;

		// FileDataSource filedatasource=null;
		// // 逐个加入附件
		// for (int j = 0; j < filenames.length; j++) {
		// filePart = new MimeBodyPart();
		// filedatasource = new FileDataSource(filenames[j]);
		// filePart.setDataHandler(new DataHandler(filedatasource));
		// try {
		// filePart.setFileName(MimeUtility.encodeText(filedatasource.getName()));
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// mm.addBodyPart(filePart);
		// filedatasource=null;
		// filePart = null;
		// }
		// 设置邮件消息的主要内容
		MimeBodyPart MessageBodyPart = new MimeBodyPart();
		MessageBodyPart.setText(mailInfo.getContent());
		mm.addBodyPart(MessageBodyPart);
		// 设置邮件发送对象mm
		mimeMessage.setContent(mm);
		// mimeMessage.saveChanges();
		// 发送邮件
		transport.send(mimeMessage);
		transport.close();
		return true;
	}

	/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 * @throws MessagingException
	 */
	public static boolean sendHtmlMail(MailSenderInfo mailInfo) throws MessagingException {

		final Properties pro = mailInfo.getProperties();
		// 如果需要身份认证，则创建一个密码验证器
		// 判断是否需要身份认证
		/*
		 * MyAuthenticator authenticator = null; if (mailInfo.isValidate()) {
		 * authenticator = new MyAuthenticator(mailInfo.getUserName(),
		 * mailInfo.getPassword()); }
		 */
		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = pro.getProperty("mail.user");
				String password = pro.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		// Session sendMailSession = Session.getInstance(pro, authenticator);

		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from = new InternetAddress(mailInfo.getFromAddress());
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);
		// 创建邮件的接收者地址，并设置到邮件消息中
		Address to = new InternetAddress(mailInfo.getToAddress());
		// Message.RecipientType.TO属性表示接收者的类型为TO
		mailMessage.setRecipient(Message.RecipientType.TO, to);
		// 设置邮件消息的主题
		mailMessage.setSubject(mailInfo.getSubject());
		// 设置邮件消息发送的时间
		mailMessage.setSentDate(new Date());
		// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		// 设置HTML内容
		html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		// 将MiniMultipart对象设置为邮件内容
		mailMessage.setContent(mainPart);
		// 发送邮件
		Transport.send(mailMessage);
		return true;

	}

	public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
		// 这个类主要是设置邮件
		/*MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setMailServerHost("smtp.126.com");
		mailInfo.setMailServerPort("25");
		mailInfo.setValidate(true);
		mailInfo.setUserName("liuxingwuji@126.com");
		mailInfo.setPassword("880123@");// 您的邮箱密码
		mailInfo.setFromAddress("liuxingwuji@126.com");
		mailInfo.setToAddress("1559444700@qq.com");
		// mailInfo.setToccAddress("fuhaiqiang123@126.com");
		// mailInfo.setTobccAddress("277533265@qq.com");
		// mailInfo.setToReplyAddress("277533265@qq.com");
		mailInfo.setSubject("测试设置邮箱标题Subject");
		mailInfo.setContent("设置邮箱内容123456789");
		// "D:\\temp\\你大爷.txt"
		// String[] fileNames
		// ={"D:\\temp\\测试.txt","D:\\temp\\债权转让及受让协议--刘勇20141016_1.pdf"};
		// mailInfo.setAttachFileNames(fileNames);
		// //"附件路径，如：F:\\笔记<a>\\struts2</a>与mvc.txt";
		// 这个类主要来发送邮件
		SimpleMailSender sms = new SimpleMailSender();
		sms.sendHtmlMail(mailInfo);// 发送文体格式
		// sms.sendHtmlMail(mailInfo);//发送html格式*/
		MailSenderInfo mailInfo = new MailSenderInfo();
		PropertiesUtil.readPropertiesFile("email.properties", mailInfo);
		System.out.println(mailInfo.getFromAddress());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	public static boolean sendThreadEmail(final MailSenderInfo mailInfo) {
		PropertiesUtil.readPropertiesFile("email.properties", mailInfo);
		final Properties pro = mailInfo.getProperties();
		
		// 如果需要身份认证，则创建一个密码验证器
		// 判断是否需要身份认证
		/*
		 * MyAuthenticator authenticator = null; if (mailInfo.isValidate()) {
		 * authenticator = new MyAuthenticator(mailInfo.getUserName(),
		 * mailInfo.getPassword()); }
		 */
		// 构建授权信息，用于进行SMTP进行身份验证
		final Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = pro.getProperty("mail.user");
				String password = pro.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session

		Runnable task = new Runnable() {

			@Override
			public void run() {

				// Session sendMailSession = Session.getInstance(pro,
				// authenticator);
				Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
				try {
					// 根据session创建一个邮件消息
					Message mailMessage = new MimeMessage(sendMailSession);
					// 创建邮件发送者地址
					Address from = new InternetAddress(mailInfo.getFromAddress());
					// 设置邮件消息的发送者
					mailMessage.setFrom(from);
					// 创建邮件的接收者地址，并设置到邮件消息中
					Address to = new InternetAddress(mailInfo.getToAddress());
					// Message.RecipientType.TO属性表示接收者的类型为TO
					mailMessage.setRecipient(Message.RecipientType.TO, to);
					// 设置邮件消息的主题
					mailMessage.setSubject(mailInfo.getSubject());
					// 设置邮件消息发送的时间
					mailMessage.setSentDate(new Date());
					// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
					Multipart mainPart = new MimeMultipart();
					// 创建一个包含HTML内容的MimeBodyPart
					BodyPart html = new MimeBodyPart();
					// 设置HTML内容
					html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
					mainPart.addBodyPart(html);
					// 将MiniMultipart对象设置为邮件内容
					mailMessage.setContent(mainPart);
					// 发送邮件
					Transport.send(mailMessage);
					
					//得到邮差对象        
					//Transport transport = session.getTransport();        
					//连接自己的邮箱账户        
					//transport.connect(mailInfo.getFromAddress(), "gpvvrzqjnfkohjij");//密码为刚才得到的授权码        

					//发送邮件        transport.sendMessage(message, message.getAllRecipients());    
				} catch (AddressException e) {
					if (logger.isErrorEnabled()) {
						logger.error(e);
					}
				} catch (MessagingException e) {
					if (logger.isErrorEnabled()) {
						logger.error(e);
					}
				}
			}

		};
		// 使用Executor框架的线程池执行邮件发送任务
		executor.execute(task);

		return true;
	}
	public static boolean sendQQEmail(final MailSenderInfo mailInfo) {
		PropertiesUtil.readPropertiesFile("email.properties", mailInfo);
		Properties properties = new Properties();

		  properties.put("mail.transport.protocol", "smtp");// 连接协议        

		  properties.put("mail.smtp.host", "smtp.qq.com");// 主机名        

		  properties.put("mail.smtp.port", 465);// 端口号        

		  properties.put("mail.smtp.auth", "true");        

		  properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接  ---一般都使用        

		  properties.put("mail.debug", "true");//设置是否显示debug信息  true 会在控制台显示相关信息        

		// 根据邮件会话属性和密码验证器构造一个发送邮件的session

		final Session session = Session.getInstance(properties);        
		
		Runnable task = new Runnable() {
			@Override
			public void run() {
				try {
					// 根据session创建一个邮件消息
					Message mailMessage = new MimeMessage(session);
					// 创建邮件发送者地址
					Address from = new InternetAddress("1922988966@qq.com");
					// 设置邮件消息的发送者
					mailMessage.setFrom(from);
					// 创建邮件的接收者地址，并设置到邮件消息中
					Address to = new InternetAddress(mailInfo.getToAddress());
					// Message.RecipientType.TO属性表示接收者的类型为TO
					mailMessage.setRecipient(Message.RecipientType.TO, to);
					// 设置邮件消息的主题
					mailMessage.setSubject(mailInfo.getSubject());
					// 设置邮件消息发送的时间
					mailMessage.setSentDate(new Date());
					// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
					Multipart mainPart = new MimeMultipart();
					// 创建一个包含HTML内容的MimeBodyPart
					BodyPart html = new MimeBodyPart();
					// 设置HTML内容
					html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
					mainPart.addBodyPart(html);
					// 将MiniMultipart对象设置为邮件内容
					mailMessage.setContent(mainPart);
					//得到邮差对象        
					Transport transport = session.getTransport();        
					//连接自己的邮箱账户        
					transport.connect("1922988966@qq.com", "tgqtykawmidrgfgh");//密码为刚才得到的授权码        
					//发送邮件        
					transport.sendMessage(mailMessage, mailMessage.getAllRecipients());    
				} catch (AddressException e) {
					if (logger.isErrorEnabled()) {
						logger.error(e);
					}
				} catch (MessagingException e) {
					if (logger.isErrorEnabled()) {
						logger.error(e);
					}
				}
			}

		};
		// 使用Executor框架的线程池执行邮件发送任务
		executor.execute(task);

		return true;
	}
}
